package models

import (
	"bufio"
	"reflect"
	"strings"
)

type CloudflareInfo struct {
	Fl          string `key:"fl"`
	H           string `key:"h"`
	Ip          string `key:"ip"`
	Ts          string `key:"ts"`
	VisitScheme string `key:"visit_scheme"`
	Uag         string `key:"uag"`
	Colo        string `key:"colo"`
	Sliver      string `key:"sliver"`
	Http        string `key:"http"`
	Loc         string `key:"loc"`
	Tls         string `key:"tls"`
	Sni         string `key:"sni"`
	Warp        string `key:"warp"`
	Gateway     string `key:"gateway"`
	Rbi         string `key:"rbi"`
	Kex         string `key:"kex"`
}

// ParseCloudflareInfo 使用反射解析字符串到结构体
func (cf *CloudflareInfo) ParseCloudflareInfo(input string) error {
	scanner := bufio.NewScanner(strings.NewReader(input))
	val := reflect.ValueOf(cf).Elem()
	typ := val.Type()

	for scanner.Scan() {
		line := scanner.Text()
		parts := strings.SplitN(line, "=", 2)
		if len(parts) != 2 {
			continue
		}

		key := parts[0]
		value := parts[1]

		for i := 0; i < val.NumField(); i++ {
			field := typ.Field(i)
			if field.Tag.Get("key") == key {
				val.Field(i).SetString(value)
				break
			}
		}
	}

	return scanner.Err()
}

func (cf *CloudflareInfo) ToIpInfo() IpInfo {
	return IpInfo{
		IP:             cf.Ip,
		Country:        "",
		City:           "",
		Asn:            "",
		AsnType:        "",
		CountryAppoint: "",
	}
}
